/**
 * GitLab服务类
 * @author zhou.xu
 * @date 2024-03-12 21:30:00
 */
package com.mayfool.gitmanager.core.service;

import com.mayfool.gitmanager.core.entity.GitLabProject;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.GitLabApiException;
import org.gitlab4j.api.models.Project;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

public class GitLabService {
    private static final GitLabService INSTANCE = new GitLabService();
    
    private GitLabService() {}
    
    public static GitLabService getInstance() {
        return INSTANCE;
    }
    
    /**
     * 获取GitLab项目列表
     */
    public List<GitLabProject> getProjects(String gitlabUrl,
                                           String username,
                                           String password) throws GitLabApiException {
        // 使用GitLab API获取项目列表
        // 这里需要添加GitLab API客户端依赖
        // 例如：org.gitlab4j:gitlab4j-api

        try (GitLabApi gitLabApi = new GitLabApi(gitlabUrl, username, password)) {
            List<Project> projects = gitLabApi.getProjectApi().getProjects();
            return projects.stream()
                    .map(this::convertToGitLabProject)
                    .collect(Collectors.toList());
        }
    }
    
    /**
     * 克隆GitLab项目
     */
    public void cloneProject(String gitlabUrl, 
                           String username, 
                           String password,
                           String projectPath, 
                           String localPath) {
        // 使用JGit执行克隆操作
        try (Git git = Git.cloneRepository()
                .setURI(gitlabUrl + "/" + projectPath + ".git")
                .setDirectory(new File(localPath))
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(
                    username, password))
                .call()) {
            // 克隆成功
        } catch (Exception e) {
            throw new RuntimeException("克隆项目失败: " + e.getMessage());
        }
    }
    
    private GitLabProject convertToGitLabProject(Project project) {
        return new GitLabProject(
            project.getName(),
            project.getPathWithNamespace(),
            project.getVisibility().toString()
        );
    }
}